package com.tsq.intelligence.provider.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class AiUtil {
    private static final String URL = "https://openapi.xfyun.cn/v2/aiui";
    private static final String APPID = "5f4475fd";
    private static final String API_KEY = "48031277d0307ab418b8f1acffe4e536";
    private static final String DATA_TYPE = "text";
//    private static final String DATA_TYPE = "audio";
//    private static final String SAMPLE_RATE= "16000";
//    // 情景模式
    private static final String SCENE = "main_box";
    // authId
    private static final String AUTH_ID = UUID.randomUUID().toString().replaceAll("-","");

    public static JSONObject aiFunction(String search){
        String curTime = System.currentTimeMillis() / 1000L + "";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("scene",SCENE);
        jsonObject.put("auth_id",AUTH_ID);
        jsonObject.put("data_type",DATA_TYPE);
//        jsonObject.put("sample_rate",SAMPLE_RATE);
        System.out.println(jsonObject.toJSONString());
        String paramBase64 = new String(Base64.encodeBase64(JSON.toJSONString(jsonObject).getBytes(StandardCharsets.UTF_8)));
        String checkSum = DigestUtils.md5Hex(API_KEY + curTime + paramBase64);

        Map<String, String> header = new HashMap<>();
        header.put("X-Appid", APPID);
        header.put("X-CurTime", curTime);
        header.put("X-Param", paramBase64);
        header.put("X-CheckSum", checkSum);
        HttpRequest request = HttpUtil.createPost(URL).charset(StandardCharsets.UTF_8);
        String body = request.addHeaders(header).body(search).execute().body();
        JSONObject bodyJson = JSONObject.parseObject(JSONObject.parseObject(body).toString());
        return bodyJson;
    }

}
